package com.test.hand.server.handler;

import com.test.hand.message.ChatRequestMessage;
import com.test.hand.message.ChatResponseMessage;
import com.test.hand.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * description 请求处理器
 *
 * @author zken
 * @CreateDate 2024/11/22 16:46:17
 */
@ChannelHandler.Sharable // 多线程支持
public class ChatRequestHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        // 获取接受方的channel
        Channel channel = SessionFactory.getSession().getChannel(msg.getTo());
        // 如果对方在线
        if (channel != null) {
            // 直接发送
            channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
        }
        // 不在线
        else {
            // 向发送发进行反馈信息
            ctx.writeAndFlush(new ChatResponseMessage(false, "对方不在线"));
        }
    }
}
